<template>
  <div class="membership-cards-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">会员卡</h1>
      <p class="page-description">
        管理会员卡折扣和次卡功能，提升客户体验和消费粘性
      </p>
    </div>

    <!-- 标签页切换 -->
    <div class="tabs-container">
      <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
        <a-tab-pane key="discount" tab="折扣卡">
          <!-- 折扣卡管理内容 -->
          <div class="tab-content">
            <!-- 操作按钮 -->
            <div class="action-bar">
              <div class="left-actions">
                <a-button type="primary" @click="showAddDiscountCardModal">
                  <template #icon><Plus /></template>
                  + 添加项目
                </a-button>
              </div>
              <div class="right-actions">
                <a-button
                  danger
                  :disabled="selectedDiscountCards.length === 0"
                  @click="handleBatchDisableDiscount"
                >
                  停用
                </a-button>
              </div>
            </div>

            <!-- 折扣卡列表 -->
            <div class="cards-table">
              <a-table
                :columns="discountColumns"
                :data-source="discountCards"
                :pagination="false"
                :row-selection="discountRowSelection"
                :loading="loading"
                size="small"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'discount'">
                    <span class="discount-value">{{ record.discount }}</span>
                  </template>
                  <template v-else-if="column.key === 'action'">
                    <a-space>
                      <a-button
                        type="link"
                        size="small"
                        @click="editDiscountCard(record)"
                      >
                        <template #icon><UserRoundPen /></template>
                        编辑
                      </a-button>
                      <a-button
                        type="link"
                        size="small"
                        danger
                        @click="disableDiscountCard(record.id)"
                      >
                        <template #icon><Trash2 /></template>
                        停用
                      </a-button>
                    </a-space>
                  </template>
                </template>
              </a-table>
            </div>
          </div>
        </a-tab-pane>

        <a-tab-pane key="service" tab="次卡">
          <!-- 次卡管理内容 -->
          <div class="tab-content">
            <!-- 操作按钮 -->
            <div class="action-bar">
              <div class="left-actions">
                <a-button type="primary" @click="showAddServiceCardModal">
                  <template #icon><Plus /></template>
                  + 添加次卡
                </a-button>
              </div>
              <div class="right-actions">
                <a-button
                  danger
                  :disabled="selectedServiceCards.length === 0"
                  @click="handleBatchDisableService"
                >
                  停用
                </a-button>
              </div>
            </div>

            <!-- 次卡列表 -->
            <div class="cards-table">
              <a-table
                :columns="serviceColumns"
                :data-source="serviceCards"
                :pagination="false"
                :row-selection="serviceRowSelection"
                :loading="loading"
                size="small"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'salesCommission'">
                    <span class="commission-value"
                      >{{ record.salesCommission }}%</span
                    >
                  </template>
                  <template v-else-if="column.key === 'serviceCommission'">
                    <span class="commission-value"
                      >¥{{ record.serviceCommission }}</span
                    >
                  </template>
                  <template v-else-if="column.key === 'action'">
                    <a-space>
                      <a-button
                        type="link"
                        size="small"
                        @click="editServiceCard(record)"
                      >
                        <template #icon><UserRoundPen /></template>
                        编辑
                      </a-button>
                      <a-button
                        type="link"
                        size="small"
                        danger
                        @click="disableServiceCard(record.id)"
                      >
                        <template #icon><Trash2 /></template>
                        停用
                      </a-button>
                    </a-space>
                  </template>
                </template>
              </a-table>
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>

    <!-- 折扣卡模态框 -->
    <DiscountCardModal
      v-model:visible="discountCardModalVisible"
      :card="currentDiscountCard"
      @save="handleDiscountCardSave"
    />

    <!-- 次卡模态框 -->
    <ServiceCardModal
      v-model:visible="serviceCardModalVisible"
      :card="currentServiceCard"
      @save="handleServiceCardSave"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import type { TableProps } from 'ant-design-vue';
import { Plus, Trash2, UserRoundPen } from '@vben/icons';

import DiscountCardModal from './components/DiscountCardModal.vue';
import ServiceCardModal from './components/ServiceCardModal.vue';

// 响应式数据
const loading = ref(false);
const activeTab = ref('discount');
const selectedDiscountCards = ref<string[]>([]);
const selectedServiceCards = ref<string[]>([]);
const currentDiscountCard = ref<any>(null);
const currentServiceCard = ref<any>(null);

// 模态框控制
const discountCardModalVisible = ref(false);
const serviceCardModalVisible = ref(false);

// 折扣卡数据
const discountCards = ref([
  {
    id: '1',
    type: '金卡',
    discount: 9.5,
    status: 'active',
  },
  {
    id: '2',
    type: '银卡',
    discount: 9.8,
    status: 'active',
  },
  {
    id: '3',
    type: '普通卡',
    discount: 10,
    status: 'active',
  },
]);

// 次卡数据
const serviceCards = ref([
  {
    id: '1',
    type: '洗澡卡',
    salesCommission: 10,
    serviceCommission: 5,
    status: 'active',
  },
  {
    id: '2',
    type: '美容卡',
    salesCommission: 15,
    serviceCommission: 8,
    status: 'active',
  },
  {
    id: '3',
    type: '护理卡',
    salesCommission: 8,
    serviceCommission: 3,
    status: 'active',
  },
]);

// 折扣卡表格列定义
const discountColumns: TableProps['columns'] = [
  {
    title: '折扣卡类型',
    dataIndex: 'type',
    key: 'type',
    width: 150,
  },
  {
    title: '卡片折扣(1-10)',
    key: 'discount',
    width: 150,
    customRender: ({ record }) => {
      const discount = record.discount;
      const discountText =
        discount === 10 ? '不打折' : `${(10 - discount) * 10}折`;
      return `${discount} (${discountText})`;
    },
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right',
  },
];

// 次卡表格列定义
const serviceColumns: TableProps['columns'] = [
  {
    title: '次卡类型',
    dataIndex: 'type',
    key: 'type',
    width: 150,
  },
  {
    title: '销售提成(%)',
    key: 'salesCommission',
    width: 120,
  },
  {
    title: '服务提成(元)',
    key: 'serviceCommission',
    width: 120,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right',
  },
];

// 折扣卡行选择配置
const discountRowSelection = reactive({
  selectedRowKeys: selectedDiscountCards,
  onChange: (keys: string[]) => {
    selectedDiscountCards.value = keys;
  },
});

// 次卡行选择配置
const serviceRowSelection = reactive({
  selectedRowKeys: selectedServiceCards,
  onChange: (keys: string[]) => {
    selectedServiceCards.value = keys;
  },
});

// 方法
const handleTabChange = (key: string) => {
  activeTab.value = key;
  // 切换标签时清空选择
  selectedDiscountCards.value = [];
  selectedServiceCards.value = [];
};

// 折扣卡操作
const showAddDiscountCardModal = () => {
  currentDiscountCard.value = null;
  discountCardModalVisible.value = true;
};

const editDiscountCard = (card: any) => {
  currentDiscountCard.value = { ...card };
  discountCardModalVisible.value = true;
};

const disableDiscountCard = async (id: string) => {
  try {
    await new Promise((resolve) => setTimeout(resolve, 500));
    const card = discountCards.value.find((c) => c.id === id);
    if (card) {
      card.status = 'disabled';
    }
    message.success('停用成功');
  } catch {
    message.error('停用失败');
  }
};

const handleBatchDisableDiscount = async () => {
  if (selectedDiscountCards.value.length === 0) {
    message.warning('请先选择要停用的折扣卡');
    return;
  }

  try {
    await new Promise((resolve) => setTimeout(resolve, 500));
    selectedDiscountCards.value.forEach((id) => {
      const card = discountCards.value.find((c) => c.id === id);
      if (card) {
        card.status = 'disabled';
      }
    });
    selectedDiscountCards.value = [];
    message.success('批量停用成功');
  } catch {
    message.error('批量停用失败');
  }
};

const handleDiscountCardSave = (card: any) => {
  if (card.id) {
    // 编辑现有折扣卡
    const index = discountCards.value.findIndex((c) => c.id === card.id);
    if (index !== -1) {
      discountCards.value[index] = { ...card };
    }
  } else {
    // 添加新折扣卡
    card.id = Date.now().toString();
    card.status = 'active';
    discountCards.value.push(card);
  }
  message.success('保存成功');
  discountCardModalVisible.value = false;
};

// 次卡操作
const showAddServiceCardModal = () => {
  currentServiceCard.value = null;
  serviceCardModalVisible.value = true;
};

const editServiceCard = (card: any) => {
  currentServiceCard.value = { ...card };
  serviceCardModalVisible.value = true;
};

const disableServiceCard = async (id: string) => {
  try {
    await new Promise((resolve) => setTimeout(resolve, 500));
    const card = serviceCards.value.find((c) => c.id === id);
    if (card) {
      card.status = 'disabled';
    }
    message.success('停用成功');
  } catch {
    message.error('停用失败');
  }
};

const handleBatchDisableService = async () => {
  if (selectedServiceCards.value.length === 0) {
    message.warning('请先选择要停用的次卡');
    return;
  }

  try {
    await new Promise((resolve) => setTimeout(resolve, 500));
    selectedServiceCards.value.forEach((id) => {
      const card = serviceCards.value.find((c) => c.id === id);
      if (card) {
        card.status = 'disabled';
      }
    });
    selectedServiceCards.value = [];
    message.success('批量停用成功');
  } catch {
    message.error('批量停用失败');
  }
};

const handleServiceCardSave = (card: any) => {
  if (card.id) {
    // 编辑现有次卡
    const index = serviceCards.value.findIndex((c) => c.id === card.id);
    if (index !== -1) {
      serviceCards.value[index] = { ...card };
    }
  } else {
    // 添加新次卡
    card.id = Date.now().toString();
    card.status = 'active';
    serviceCards.value.push(card);
  }
  message.success('保存成功');
  serviceCardModalVisible.value = false;
};

// 页面初始化
onMounted(() => {
  loading.value = false;
});
</script>

<style scoped>
.membership-cards-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.page-header {
  background: white;
  padding: 24px;
  border-bottom: 1px solid #e8e8e8;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.page-description {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.tabs-container {
  flex: 1;
  background: white;
  margin: 16px;
  border-radius: 8px;
  overflow: hidden;
}

.tab-content {
  padding: 24px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.left-actions {
  display: flex;
  gap: 8px;
}

.cards-table {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.discount-value {
  font-weight: 500;
  color: #1890ff;
}

.commission-value {
  font-weight: 500;
  color: #52c41a;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .left-actions {
    justify-content: center;
  }

  .tabs-container {
    margin: 8px;
  }

  .tab-content {
    padding: 16px;
  }
}
</style>
